<template>
  <div class="page">
    <div v-if="loginWay !== 'weChat' && loginWay !== 'firstBind'" class="login-wrapper">
      <div class="login-way-warpper">
        <span class="login-way" :class="loginWay ==='password' ? 'active' : ''" @click="changeLoginWay('password')">账号密码登录</span>
        <span class="login-way" :class="loginWay ==='captcha' ? 'active' : ''"
              @click="changeLoginWay('captcha')">验证码登录</span>
      </div>
      <!--账号密码登录-->
      <div class="login" v-if="loginWay === 'password'" :key="'login'">
        <el-form ref="formValidate" :model="formValidate" :rules="ruleValidate">
          <el-form-item prop="username">
            <el-input class="has-prefix" prefix-icon="el-icon-user-solid" :maxlength="50" v-model="formValidate.username" placeholder="请输入账号"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              class="has-prefix"
              prefix-icon="el-icon-lock"
              :type="'password'"
              :minlength="6"
              :maxlength="20"
              v-model="formValidate.password"
              placeholder="请输入密码"
            >
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="success" class="submit" @click="handleSubmit('formValidate')">登&nbsp;&nbsp;录</el-button>
          </el-form-item>
          <div class="login-wrapper-agreement">
            <el-checkbox v-model="isAgreement">已阅读并同意
              <span style="color:dodgerblue" @click.prevent="goToAgreement('user')">《用户协议》</span>
              和&nbsp;<span style="color:dodgerblue" @click.prevent="goToAgreement('privacy')">《隐私政策》</span>
            </el-checkbox>
          </div>
        </el-form>
      </div>
      <!--验证码登录-->
      <div class="login" v-if="loginWay==='captcha'" :key="'captcha'">
        <el-form ref="captchaValidate" :model="captchaValidate" :rules="ruleValidate">
          <el-form-item prop="phone">
            <el-input class="has-prefix" prefix-icon="el-icon-user-solid" v-model="captchaValidate.phone" placeholder="请输入账号"></el-input>
          </el-form-item>
          <el-form-item prop="captcha">
            <el-input
              class="has-prefix"
              v-model="captchaValidate.captcha"
              placeholder="请输入验证码"
              prefix-icon="el-icon-lock"
            >
              <el-button slot="append" class="captcha">
                <span v-if="showCode" @click="getCode">获取验证码</span>
                <span v-if="!showCode">{{ second }}s后重发</span>
              </el-button>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="success" class="submit" @click="handleCaptchaSubmit('captchaValidate')">登&nbsp;&nbsp;录</el-button>
          </el-form-item>
        </el-form>
        <div class="login-wrapper-agreement">
          <el-checkbox v-model="isAgreement">已阅读并同意
            <span style="color:dodgerblue" @click.prevent="goToAgreement('user')">《用户协议》</span>
            和&nbsp;<span style="color:dodgerblue" @click.prevent="goToAgreement('privacy')">《隐私政策》</span>
          </el-checkbox>
        </div>
      </div>

      <div class="login-wrapper-footer">
        <div class="or">
          <p class="line"></p>
          <p class="text">或</p>
          <p class="line"></p>
        </div>
        <div class="wx-login">
          <img @click="changeLoginWay('weChat')" class="wx-logo" src="../assets/images/btn_login_wechat.png" />
        </div>
      </div>
    </div>
    <div v-show="loginWay === 'weChat'" class="login-wrapper">
      <div id="login_container"></div>
      <div>
        <el-button type="text" class="change-way" @click="loginWay = 'password'">密码登录</el-button>&nbsp;
        |<el-button type="text" class="change-way" @click="loginWay = 'captcha'">验证码登录</el-button>
      </div>
    </div>
    <div v-show="loginWay == 'firstBind'">
      <first-login :platform-code="platformCode"></first-login>
    </div>
  </div>
</template>

<script>
const md5 = require('js-md5')
const LOGIN_URL = '/api/agent/authenticateByPhoneAndPassword'
// const IP = returnCitySN['cip']
import '@/framework/utils/wxLogin'
import {post} from '@/framework/http/request'
import { authenticateByOpenCode, sendCaptchaByType,authenticateByPhoneAndCaptcha } from "../service/manager"
import FirstLogin from "@/framework/first-login/firstLogin";
import {mapActions} from "vuex"

export default {
  name: 'Login',
  data() {
    const phoneValidator = (rule, value, callback) => {
      let reg = /^1[3456789][0-9]{9}$/
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('手机号不合法'))
      }
    }
    return {
      loginWay: this.$store.state.loginWay || 'password',   //登录方式
      formValidate: {},
      ruleValidate: {
        username: [{required: true, message: '用户名不能为空', trigger: 'blur'}],
        password: [{required: true, message: '登录密码不能为空', trigger: 'blur'}],
        phone: [{required: true, message: '手机号不能为空', trigger: 'blur'},{validator: phoneValidator, trigger: 'blur'}],
        captcha: [{required: true, message: '验证码不能为空', trigger: 'blur'}],
      },
      captchaValidate: {},
      platformCode: '',  //微信临时授权code
      showCode: true,
      second: 60,
      interval: null,
      isAgreement: this.$store.state.isAgreement || false, //是否同意协议
    }
  },
  components:{FirstLogin},
  watch: {
    second(val) {
      if (val === 0) {
        clearInterval(this.interval)
        this.showCode = true
        this.second = 60
      }
    },
    //监听url的变化
    $route:{
      handler(val){
        console.log('路径变化')
        console.log('授权码：'+val.query.code)
        //如果地址栏发生改变，该函数会执行
        //获取微信临时授权code
        this.platformCode = val.query.code
        if(this.platformCode) {
          this.handleWechatLogin()
        }
      }
    }
  },
  methods: {
    //切换登录方式
    changeLoginWay(val) {
      // this.isAgreement = false
      this.loginWay = val
      if(val === 'weChat') {
        this.wechatLogin()
      }
    },
    // 获取验证码
    getCode() {
      let reg = /^1[3456789][0-9]{9}$/
      if(reg.test(this.captchaValidate.phone)){
        sendCaptchaByType({phone: this.captchaValidate.phone, type: 'login'}, res=> {})
        this.showCode = false
        this.countDown()
      } else {
        this.$message.error('手机号不合法')
      }
    },
    // 验证码获取倒计时
    countDown() {
      this.interval = setInterval(() => {
        this.second--
      }, 1000)
    },
    // 验证码登录
    handleCaptchaSubmit(name) {
      if(this.isAgreement){
        this.$refs[name].validate(valid=> {
          if(valid){
            this.captchaValidate.type = 'web'
            authenticateByPhoneAndCaptcha(this.captchaValidate,data => {
              console.log(data)
              const { token } = data
              localStorage.setItem('agent_live_web_token', token)
              this.findWithMe()
              this.$router.push('/index')
            })
          }
        })
      }else{
        this.$message({
          showClose: true,
          message: '请同意协议',
          type: 'warning'
        });
      }
    },
    //展示二维码
    wechatLogin() {
      let that = this
        new WxLogin({
          self_redirect: false,
          id: "login_container",
          appid: "wxce06ae7064d6529c",
          scope: "snsapi_login",
          // redirect_uri: encodeURIComponent(that.$store.state.targetUrl + '/login'),
          redirect_uri: encodeURIComponent(that.$store.state.targetUrl + '/login'),
          state: "",
          style: ""
        })
    },
    //微信登录
    handleWechatLogin() {
      authenticateByOpenCode({platformCode: this.platformCode}, data=> {
        console.log('登录返回：')
        console.log(data)
        const {token,firstBindPhone} = data
        //用户第一次绑定微信
        if(firstBindPhone == 'false'){
          localStorage.setItem('agent_live_web_token', token)
          this.findWithMe()
          this.$router.push('/index')
        }else{
          // this.$router.push('/login/bind/'+this.platformCode)
          this.loginWay = 'firstBind'
        }
      })
    },
    //账号密码登录
    handleSubmit(name) {
      if(this.isAgreement){
        this.$refs[name].validate(valid => {
          if (valid) {
            // 如果校验成功则发送登录请求
            let param = {
              phone: this.formValidate.username,
              password: this.formValidate.password,
              type:"web"
            }
            // 这里是用axios封装的post方法，第一个参数是路径，第二个参数是参数，第三是回调函数，数据存储在回调中
            post(LOGIN_URL, param, data => {
              const { token } = data
              console.log('token: '+ token)
              localStorage.setItem('agent_live_web_token', token)
              this.findWithMe()
              this.$router.push('/index')
            })
          }
        })
      }else{
        this.$message({
          showClose: true,
          message: '请同意协议',
          type: 'warning'
        });
      }
    },
    findWithMe() {
      // 获取左侧菜单项
      // post('/api/agent/findWithMe', {client: 'MANAGER_WEB'}, menuData => {
      //   console.log(menuData)
      //   this.$root.$emit('MENULIST', menuData)
      //   localStorage.menuList = JSON.stringify(menuData)
      // })
      // post('/api/manager/findWithMe',{},res => {
      //   this.$store.commit('SAVE_USER', res)
      //   this.$store.dispatch('SAVE_USER_CACHE', res)
      //   this.$router.push('/index')
      // })

      post('/api/agent/findWithMe',{},data => {
        console.log(data)
        this.$store.commit('SAVE_USER', data)
        this.$store.dispatch('SAVE_USER_CACHE', data)
      })
    },
    goToAgreement(type){
      this.$store.commit('IS_AGREEMENT', this.isAgreement)
      this.$store.commit('LOGIN_WAY',this.loginWay)
      //进入用户协议
      if(type == "user"){
        this.$router.push({
          name:"agreement",
          params:{
            type:'用户协议',
          }
        })
      }else{ //进入隐私协议
        this.$router.push({
          name:"agreement",
          params:{
            type:'隐私协议',
          }
        })
      }
    },
    //  微信二维码绑定对话框返回
    cancel(){
      this.loginWay = 'password'
    }
  },
  beforeRouteLeave(to, from, next) {
    // 路由离开之前清除导航激活状态
    if (window.sessionStorage) {
      sessionStorage.clear()
    }
    next()
  }
}
</script>
<style lang="less" scoped>
.page {
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: -40px;

  .login-wrapper {
    width: 480px;
    margin: 0 auto;
    padding: 40px;
    background: #f5f7fa;
    text-align: center;
    box-shadow: 0 0 10px rgba(0, 0, 0, .2);

    .login-way-warpper {
      width: 400px;
      margin: 0 auto 40px;
      display: flex;
      text-align: center;
      justify-content: space-between;

      .login-way {
        padding-bottom: 10px;
        cursor:pointer;
      }

      .active {
        color: #009688;
        border-bottom: 1px solid #009688;
      }
    }

    .login {
      width: 400px;
      margin: 0 auto;

      .el-button--success {
        margin-top: 20px;
        background: #19be6b;
        width: 100%;
        height: 40px;
        font-size: 16px;

        &.hover {
          background: #19be6f;
        }
      }

      .forget-btn-wrapper {
        margin: 10px 0;
        display: flex;
        justify-content: flex-end;
      }
    }
    .login-wrapper-agreement {
      width: 100%;
      display: flex;
      margin-top: 20px;
    }
    .captcha {
      background: #1890ff;
      color: #FFFFFF;
      height: 40px;
    }
    .login-wrapper-footer {
      width: 400px;
      margin: 40px auto 0;
      .or {
        display: flex;
        justify-content: center;
        align-items: center;
        .line {
          height: 1px;
          width: 180px;
          border-top: 0.5px solid #2c3e50;
        }
        .text {
          padding: 0 10px;
        }
      }
      .wx-login {
        text-align: center;
        margin-top: 20px;
        .wx-logo {
          width: 50px;
          height: 50px;
          cursor:pointer;
        }
      }
    }

    .change-way{
      font-size: 15px;
    }
  }

  .qrCode{
    text-align: center;
  }
}

.el-input {
  width: 100%;
}
/deep/ .el-input__inner {
  height: 40px;
  line-height: 40px;
  font-size: 14px;
}
.el-form-item {
  margin-top: 20px;
}
</style>
